import {
  getDevelopInfo,
  getDevelopPhoneCode,
  getDevelopSettingsToken,
  modifyAppKey,
  modifyWhiteIP,
  openApp,
  viewAPI,
} from '@/services/account-center';
import { useModel } from '@umijs/max';
import {
  Alert,
  Button,
  Card,
  Col,
  Form,
  Input,
  Modal,
  Row,
  Typography,
  message,
} from 'antd';
import { useEffect, useState } from 'react';
const { Paragraph } = Typography;

let timer: any = null;

const DevelopSetting = () => {
  const { initialState } = useModel('@@initialState');
  const [disable, setDisable] = useState(false);
  const [openASForm, setOpenASForm] = useState(false);
  const [openIPModal, setOpenIPModal] = useState(false);
  const [countDown, setCountDown] = useState(60);
  const [type, setType] = useState<string | undefined>(undefined);
  const [form] = Form.useForm();
  const [openLoading, setOpenLoading] = useState(false);
  const [developInfo, setDevelopInfo] = useState<
    Partial<{
      appId: string;
      status: number;
      appPublicKeyIsSet: boolean;
      whiteIpsIsSet: boolean;
    }>
  >();
  useEffect(() => {
    getDevelopInfo().then((res) => {
      setDevelopInfo(res || {});
    });
  }, []);
  const [loading, setLoading] = useState(false);
  const [ASForm, setASForm] = useState({
    appPublicKey: '',
    publicKey: '',
    whiteIps: [''],
  });

  useEffect(() => {
    if (disable) {
      timer = setInterval(() => {
        setCountDown((countDown: number) => {
          if (countDown === 1) {
            setDisable(false);
            clearInterval(timer);
            return 60;
          }
          return countDown - 1;
        });
      }, 1000);
    }
  }, [disable]);

  const [openModal, setOpenModal] = useState(false);

  const viewAPIFn = (type?: any) => {
    setType(type);
    viewAPI({
      token: localStorage.getItem('DEV_TOEKN'),
    }).then((res: any) => {
      if (res.success) {
        setASForm({
          appPublicKey: res.data.appPublicKey,
          publicKey: res.data.publicKey,
          whiteIps: res.data.whiteIps,
        });
        if (!type) {
          setOpenASForm(true);
        } else {
          setOpenIPModal(true);
        }
      } else {
        if (res.resultCode === 'user.invalid_dev_token') {
          localStorage.removeItem('DEV_TOEKN');
          setOpenModal(true);
        } else {
          message.error(res.resultMessage);
        }
      }
    });
  };

  return (
    <div className="flex flex-col gap-6">
      <Card title="应用信息">
        <Paragraph className="mt-4" copyable={{ text: developInfo?.appId }}>
          appId: {developInfo?.appId}
        </Paragraph>
        {developInfo?.appId && (
          <div className="flex items-center gap-4">
            <Alert
              showIcon
              type={`${Number(developInfo?.status) ? 'success' : 'warning'}`}
              message={`${
                Number(developInfo?.status) === 1
                  ? '应用状态：已上线'
                  : '应用状态：未上线'
              }`}
              className="w-44"
            />
            {Number(developInfo?.status) === 0 && (
              <Button
                type="primary"
                onClick={() => {
                  setOpenLoading(true);
                  openApp()
                    .then((res: any) => {
                      if (res.success) {
                        message.success('应用上线成功');
                      } else {
                        message.error(res.resultMessage);
                      }
                    })
                    .finally(() => {
                      setOpenLoading(false);
                    });
                }}
                loading={openLoading}
              >
                应用上线
              </Button>
            )}
          </div>
        )}
      </Card>
      <Card title="开发设置">
        <div className="flex items-center">
          <div className="flex-1 font-bold text-[18px]">接口加签</div>
          <div className="w-[50%]">
            使用公私钥的接口加签方式，用于保障应用和开放平台通信的安全性。若不设置，则无法调用接口
          </div>
          <div className="flex-1 text-center">已设置</div>
          <div
            className="flex-1 text-center text-[#00bdff] cursor-pointer"
            onClick={() => {
              viewAPIFn();
            }}
          >
            查看
          </div>
        </div>
        <div className="flex items-center mt-6">
          <div className="flex-1 font-bold text-[18px]">服务器白名单</div>
          <div className="w-[50%]">
            开发者可以配置IP地址白名单，平台将基于开发者配置的IP地址，校验开发者请求的来源IP，若来源IP不在配置的白名单范围内，平台将拦截对应的请求。选填，若不设置，则平台默认不进行任何拦截
          </div>
          <div className="flex-1 text-center">已设置</div>
          <div
            className="flex-1 text-center text-[#00bdff] cursor-pointer"
            onClick={() => {
              viewAPIFn('ip');
            }}
          >
            查看
          </div>
        </div>
      </Card>
      <Modal
        destroyOnClose
        title="短信验证"
        open={openModal}
        onCancel={() => {
          setOpenModal(false);
        }}
        okButtonProps={{
          loading,
        }}
        onOk={async () => {
          await form.validateFields();
          setLoading(true);
          const res = form.getFieldsValue();
          getDevelopSettingsToken(res)
            .then((res: any) => {
              if (res.success) {
                localStorage.setItem('DEV_TOEKN', res.data);
                viewAPIFn(type);
                setOpenModal(false);
              } else {
                message.error(res.resultMessage);
              }
            })
            .finally(() => {
              setLoading(false);
            });
        }}
      >
        <div className="my-8 pl-4">
          手机号：{initialState?.currentUser.mobile}
        </div>
        <Form form={form}>
          <Row gutter={16}>
            <Col>
              <Form.Item
                rules={[{ required: true, message: '请输入验证码' }]}
                label="验证码"
                name={'checkCode'}
              >
                <Input placeholder="请输入验证码" />
              </Form.Item>
            </Col>
            <Col>
              <Button
                disabled={disable}
                onClick={async () => {
                  try {
                    const res = (await getDevelopPhoneCode()) as any;
                    if (res.success) {
                      setDisable(true);
                      message.success('发送成功');
                    } else {
                      message.error('发送验证码失败');
                    }
                  } catch (error) {
                    message.error('发送验证码失败');
                  }
                }}
              >
                {disable ? `${countDown}秒后重新发送` : '发送验证码'}
              </Button>
            </Col>
          </Row>
        </Form>
      </Modal>
      <Modal
        open={openASForm}
        onCancel={() => {
          setOpenASForm(false);
        }}
        title="接口加签"
        okButtonProps={{
          loading,
        }}
        maskClosable={false}
        onOk={async () => {
          await form.validateFields();
          setLoading(true);
          modifyAppKey({
            appPublicKey: form.getFieldsValue().appPublicKey,
            token: localStorage.getItem('DEV_TOEKN') as string,
          })
            .then((res: any) => {
              if (res.success) {
                message.success('修改成功');
                setOpenASForm(false);
              } else {
                message.error(res.resultMessage);
              }
            })
            .finally(() => {
              setLoading(false);
            });
        }}
        destroyOnClose
      >
        <Form form={form}>
          <Row align={'middle'}>
            <Col span={22}>
              <Form.Item
                name="appPublicKey"
                label="应用公钥"
                initialValue={ASForm.appPublicKey}
                rules={[{ required: true, message: '请输入应用公钥' }]}
              >
                <Input.TextArea />
              </Form.Item>
            </Col>
            <Col>
              <Paragraph copyable={{ text: ASForm.appPublicKey }}></Paragraph>
            </Col>
          </Row>
          <Row align={'middle'}>
            <Col span={22}>
              <Form.Item
                label="平台公钥"
                name={'publicKey'}
                initialValue={ASForm.publicKey}
                required
              >
                <Input.TextArea disabled />
              </Form.Item>
            </Col>
            <Col>
              <Paragraph copyable={{ text: ASForm.publicKey }}></Paragraph>
            </Col>
          </Row>
        </Form>
      </Modal>
      <Modal
        open={openIPModal}
        onCancel={() => {
          setOpenIPModal(false);
        }}
        destroyOnClose
        title="服务器IP白名单"
        maskClosable={false}
        okButtonProps={{
          loading,
        }}
        onOk={async () => {
          await form.validateFields();
          setLoading(true);
          modifyWhiteIP({
            token: localStorage.getItem('DEV_TOEKN') as string,
            whiteIps: form.getFieldsValue().whiteIps,
          })
            .then((res: any) => {
              console.log(res);
              if (res.success) {
                message.success('处理成功');
                setOpenIPModal(false);
              } else {
                message.error(res.resultMessage);
              }
            })
            .finally(() => {
              setLoading(false);
            });
        }}
      >
        <Form form={form}>
          <Form.Item
            rules={[
              {
                required: true,
                message: '请输入ip白名单，多个ip用英文逗号隔开，最多输入10个ip',
              },
            ]}
            label="IP白名单"
            name="whiteIps"
            initialValue={ASForm.whiteIps}
          >
            <Input.TextArea />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DevelopSetting;
